package com.zjxf.resource.impl;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.zjxf.base.bean.ro.RoFileInfo;
import com.zjxf.base.common.OperationException;
import com.zjxf.resource.ResourceManagerInterfaceService;
import com.zjxf.resource.ResourceMangerUtils;
import com.zjxf.resource.properties.ResourceMangerProperties;
import com.zjxf.resource.url.ResourceManagerUrlConstants;
import com.zjxf.utils.HttpClientUtils;
import com.zjxf.utils.RSAUtils;
import lombok.AllArgsConstructor;
import org.apache.commons.codec.binary.Base64;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.io.OutputStream;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 *
 * @author zhanghao
 * date: 2019/2/21 13:57
 * description:
 */
@AllArgsConstructor
@Component
public class ResourceManagerInterfaceServiceImpl implements ResourceManagerInterfaceService {

    private final ResourceMangerProperties resourceMangerProperties;

    private String spliceUrl(String url) {
        return resourceMangerProperties.getHost() + url;
    }

    public Map<String, String> createdHeader(String publicKey, String prefix, String suffix) {
        long timeMillis = System.currentTimeMillis();

        byte[] code1 = new byte[0];
        try {
            code1 = RSAUtils.encryptByPublicKey((prefix + timeMillis + suffix).getBytes(), Base64.decodeBase64(publicKey));
        } catch (Exception e) {
            e.printStackTrace();
        }
        String token = Base64.encodeBase64String(code1);
        Map<String, String> headerMap = Maps.newHashMap();
        headerMap.put("authorization", token);
        headerMap.put("timestamp", String.valueOf(timeMillis));
        return headerMap;
    }

    private Map<String, String> getHeaderMap() {
        ResourceMangerProperties.RSA rsa = resourceMangerProperties.getRsa();
        return createdHeader(rsa.getPublicKey(), rsa.getPrefix(), rsa.getSuffix());
    }

    @Override
    public String uploadFile(JSONObject param, HttpServletRequest request) throws OperationException {
        String url = ResourceManagerUrlConstants.PUSH_RESOURCE_BY_VR;
        return resourceMangerProperties.getHost()
                .concat(ResourceManagerUrlConstants.ONLINE_FILE_RANGE)
                .concat(getResourceFileId(HttpClientUtils.getInstance().httpPostUploadFile(spliceUrl(url), getHeaderMap(), param.getInnerMap(), request)).toString());
    }

    @Override
    public String uploadFile(HttpServletRequest request) throws OperationException {
        String url = ResourceManagerUrlConstants.PUSH_RESOURCE_BY_REQUEST;
        return resourceMangerProperties.getHost()
                .concat(ResourceManagerUrlConstants.ONLINE_FILE_RANGE)
                .concat(getResourceFileId(HttpClientUtils.getInstance().httpPostUploadFile(spliceUrl(url), getHeaderMap(), Maps.newHashMap(), request)).toString());
    }

    @Override
    public String uploadFiles(HttpServletRequest request) throws Exception {
        String url = ResourceManagerUrlConstants.PUSH_RESOURCES_BY_REQUEST;
        return resourceMangerProperties.getHost()
                .concat(ResourceManagerUrlConstants.ONLINE_FILE_RANGE)
                .concat(getResourceFileId(HttpClientUtils.getInstance().httpPostUploadFile(spliceUrl(url), getHeaderMap(), Maps.newHashMap(), request)).toString());
    }

    @Override
    public  String onLineFile(HttpServletRequest request,String md5) {
        String url = ResourceManagerUrlConstants.ONLINE_FILE;
        return resourceMangerProperties.getHost()
                .concat(ResourceManagerUrlConstants.ONLINE_FILE)
                .concat(md5);
    }

    @Override
    public void downFile(JSONObject params, OutputStream out) {
        String url = ResourceManagerUrlConstants.DOWN_FILE;
        HttpClientUtils.getInstance().httpGetDownFile(spliceUrl(url), getHeaderMap(), params.getInnerMap(), out);
    }

    @Override
    public RoFileInfo findFileInfo(JSONObject params) throws OperationException {
        String url = ResourceManagerUrlConstants.FIND_BY_MD5;
        return getResourceFileInfo(HttpClientUtils.getInstance().httpPostFrom(spliceUrl(url), getHeaderMap(), params.getInnerMap()));
    }

    @Override
    public void updateFileName(JSONObject params){
        String url = ResourceManagerUrlConstants.CHANGE_FILE_INFO;
        HttpClientUtils.getInstance().httpPostFrom(spliceUrl(url), getHeaderMap(), params.getInnerMap());
    }

    /**
     * 获取返回值的
     *
     * @param responseStr 返回参数
     * @return String
     * @throws OperationException 自定义异常信息
     */
    public Object getResourceFileId(String responseStr) throws OperationException {
        JSONObject responseJson = JSONObject.parseObject(responseStr);
        if (responseJson.getBoolean("success")) {
            return responseJson.get("data");
        } else {
            throw new OperationException(responseJson.getString("msg"));
        }
    }

    /**
     * 获取返回值的
     *
     * @param responseStr 返回参数
     * @return String
     * @throws OperationException 自定义异常信息
     */
    public RoFileInfo getResourceFileInfo(String responseStr) throws OperationException {
        JSONObject responseJson = JSONObject.parseObject(responseStr);
        if (responseJson.getBoolean("success")) {
            return JSONObject.parseObject(responseJson.getString("data"), RoFileInfo.class);
        } else {
            throw new OperationException(responseJson.getString("msg"));
        }
    }
}
